import { AddArticleCommnet, ArticleComment, ArticleCommentItem, ArticlesDetail } from '@/types/data.d.'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

// state变量类型
export interface articleState {
  article: ArticlesDetail
  comment: ArticleComment
  commentList: ArticleCommentItem[] | []
}
export const article = createSlice({
  // 命名空间，在调用action的时候会默认的设置为action命令的前缀,避免冲突
  name: 'article',
  // 1. 定义变量(状态数据)
  initialState: {
    article: {
      art_id: '',
      title: '',
      pubdate: '',
      aut_id: '',
      aut_name: '',
      aut_photo: '',
    },
    comment: {
      total_count: 0,
      end_id: '',
      last_id: '',
      results: [{
        com_id: '',
        aut_id: '',
        aut_name: '',
        aut_photo: '',
        like_count: 0,
        reply_count: 0,
        pubdate: '',
        content: '',
        is_liking: true,
        is_followed: true,
      }],
    },
    commentList: [],
  } as articleState,
  // 2. 定义reducers更新变量(其中函数属性名作为action，在组件中可以dispatch触发reducer函数更新状态)
  reducers: {
    add(state, action: PayloadAction<ArticlesDetail | undefined>) {
      state.article = action.payload!
    },
    change(state, action: PayloadAction<Partial<ArticlesDetail> | undefined>) {
      state.article = {
        ...state.article,
        ...action.payload
      }
    },
    setComment(state, action: PayloadAction<ArticleComment | undefined>) {
      state.comment = { ...state.comment, ...action.payload! }
      state.commentList = [...state.commentList, ...action.payload!.results]
    },
    addComment(state, action: PayloadAction<AddArticleCommnet>) {
      if (state.commentList.length > 0) {
        state.commentList = [action.payload.new_obj, ...state.commentList,]
      }
    },
  },
})

// 导出action函数(组件中可以dispatch(action函数)触发reducer更新状态)
export const { add, change, setComment, addComment } = article.actions



// 导出reducer(创建store使用)
export default article.reducer